<?php

namespace App\Http\Middleware;

use Closure;
use App\Model\User;
use App\Model\Role;
use App\Model\Permission;
use Session;

class HasRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $route = \Route::current()->getActionName();
        // dd($route);

        if (!empty(session('user'))) {
            # code...
            $user = User::find(session('user')[0]->id);
            $roles = $user->role;

            $arr = [];
            foreach ($roles as $role) {
                # code...
                $permission = $role->permission;
                foreach ($permission as $k => $v) {
                    # code...
                    $arr[] = $v->per_url;
                }
            }

            $arr = array_unique($arr);
            // dd($arr);
            
            if (in_array($route, $arr)) {
                # code...
                return $next($request);
            }else{
                return redirect('noaccess');
            }
        }else{
            return redirect('admin/login');
        }
    }
}
